/**
 * epoll同时处理TCP请求和UDP请求的回射服务器程序
 * @date 2021/07/19
 * @author Martin Zhang(zhangming_233@163.com)
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

#define MAX_EVENT_NUMBER  1024
#define TCP_BUFFER_SIZE   512
#define UDP_BUFFER_SIZE   1024

int setnonblocking(int fd)
{
    int old_opt = fcntl(fd, F_GETFL);
    int new_opt = old_opt | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_opt);
    return old_opt;
}

void addfd(int epollfd, int fd)
{
    struct epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET;
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);

    setnonblocking(fd); /* use epoll listen events, no need to use events' blocking function */
}

int main(int argc, char *argv[])
{
    if (argc <= 2) {
        fprintf(stderr, "usage: %s ip_address port_number\n", argv[0]);
        return 1;
    }

    const char* ip = argv[1];
    int port = atoi(argv[2]);

    printf("server ip address: %s, port: %d\n", ip, port);

    int ret = 0;

    /* create TCP socket, and bind ip & port */
    struct sockaddr_in servaddr;
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &servaddr.sin_addr);
    servaddr.sin_port = htons(port);

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenfd != -1);
    
    int reuse = 1;
    ret = setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    assert(ret != -1);

    ret = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    assert(ret != -1);

    ret = listen(listenfd, 5);
    assert(ret != -1);

    /* create UDP socket, and bind ip & port */
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &servaddr.sin_addr);
    servaddr.sin_port = htons(port);

    int udpfd = socket(AF_INET, SOCK_DGRAM, 0);
    assert(udpfd >= 0);

    ret = bind(udpfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
    assert(ret != -1);

    struct epoll_event events[MAX_EVENT_NUMBER];
    int epollfd = epoll_create(5);
    assert(epollfd != -1);

    /* register readable event on TCP socket, UDP socket */
    addfd(epollfd, listenfd);
    addfd(epollfd, udpfd);

    while (1) {
        int number = epoll_wait(epollfd, events, MAX_EVENT_NUMBER, -1);
        if (number < 0) {
            printf("epoll failure\n");
            break;
        }

        for (int i = 0; i < number; ++i) {
            int sockfd = events[i].data.fd;
            if (sockfd == listenfd) { /* TCP connection */
                struct sockaddr_in cliaddr;
                socklen_t clilen = sizeof(cliaddr);
                int connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);

                addfd(epollfd, connfd); /* register connfd event(readable data, ET mode) to epollfd  */
            }
            else if (sockfd == udpfd) { /* UDP data */
                char buf[UDP_BUFFER_SIZE];

                memset(buf, '\0', UDP_BUFFER_SIZE);
                struct sockaddr_in cliaddr;
                socklen_t clilen = sizeof(cliaddr);

                ret = recvfrom(udpfd, buf, UDP_BUFFER_SIZE - 1, 0, 
                (struct sockaddr *)&cliaddr, &clilen);
                if (ret > 0) {
                    sendto(udpfd, buf, UDP_BUFFER_SIZE - 1, 0, (struct sockaddr *)&cliaddr, clilen);
                }
            }
            else if (events[i].events & EPOLLIN) { /* TCP data to read */
                char buf[TCP_BUFFER_SIZE];

                while (1) {
                    memset(buf, '\0', TCP_BUFFER_SIZE);
                    ret = recv(sockfd, buf, TCP_BUFFER_SIZE - 1, 0);
                    if (ret < 0) {/* error */
                        if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) break;

                        close(sockfd);
                        break;
                    }
                    else if (ret == 0) close(sockfd); /* peer shutdown/close */
                    else send(sockfd, buf, ret, 0); /* echo received data */
                }
            }
            else {
                printf("something else happened\n");
            }
        }
    }

    close(listenfd);
    return 0;
}

